package ljl.alg.wangzheng_camp.round1.backtrack;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* 一个典型的回溯
 * 对于每个数字，获取到对应的字母序列，遍历字母序列
 *      每个字母添加到当前结果中，
 *      进行下一个位置的数字
 *      删除当前字母
 *
* */
public class _17_letter_combination {
    
    Map<Character, String> mapping;
    List<String> res = new ArrayList<>();
    public List<String> letterCombinations(String digits) {
        if (digits.length() == 0) return res;
        Map<Character, String> mapping = new HashMap<>();
        mapping. put('2', "abc");
        mapping. put('3', "def");
        mapping. put('4', "ghi");
        mapping. put('5', "jkl");
        mapping. put('6', "mno");
        mapping. put('7', "pqrs");
        mapping. put('8', "tuv");
        mapping. put('9', "wxyz");
        this.mapping = mapping;
        backtrack(digits, 0, new StringBuilder());
        return res;
    }
    
    void backtrack(String digits, int i, StringBuilder buffer) {
        if (i == digits.length()) {
            res.add(buffer.toString());
        } else {
            char digit = digits.charAt(i);
            String letters = mapping.get(digit);
            for (int j = 0; j < letters.length(); j++) {
                buffer.append(letters.charAt(j));
                backtrack(digits, i + 1, buffer);
                buffer.deleteCharAt(i);
            }
        }
    }
    
}
